package com.example.klinemqflink.service;

import com.example.klinemqflink.model.MarketData;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQTopicProducer {
    private static final String EXCHANGE_NAME = "topic_trades";
    private static final String[] ROUTING_KEYS = {"stocks.AAPL", "stocks.GOOG", "cryptos.BTC", "cryptos.ETH"};

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");

        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            // 声明 topic 交换机
            channel.exchangeDeclare(EXCHANGE_NAME, "topic");

            ObjectMapper objectMapper = new ObjectMapper();
            for (int i = 0; i < 10; i++) {
                for (String routingKey : ROUTING_KEYS) {
                    MarketData message = new MarketData();
                    message.setSymbol(routingKey.split("\\.")[1]);
                    message.setPrice(Math.random() * 1000);
                    message.setTimestamp(System.currentTimeMillis());

                    String jsonMessage = objectMapper.writeValueAsString(message);
                    channel.basicPublish(EXCHANGE_NAME, routingKey, null, jsonMessage.getBytes());
                    System.out.println(" [x] Sent '" + routingKey + "':'" + jsonMessage + "'");
                }
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
